package com.lsfb.light.Video;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alivc.player.AliVcMediaPlayer;
import com.alivc.player.MediaPlayer;
import com.alivc.player.VcPlayerLog;
import com.aliyun.vodplayerview.utils.NetWatchdog;
import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.lsfb.light.R;
import com.lsfb.light.Utils.Formatter;
import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInjectUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;

import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2018/4/16 0016.
 */
public class VideoActivity extends Activity {

    @ViewInject(R.id.surfaceView)
    private SurfaceView mSurfaceView;

    @ViewInject(R.id.progress_layout)
    private LinearLayout progress_layout;

    @ViewInject(R.id.currentPosition)
    private TextView positionTxt;

    @ViewInject(R.id.progress)
    private SeekBar progressBar;

    @ViewInject(R.id.totalDuration)
    private TextView durationTxt;

    @ViewInject(R.id.quanpin)
    private Button quanpin;

    @ViewInject(R.id.aniu)
    private TextView aniu;

    /**
     * 沉浸式
     */
    protected ImmersionBar mImmersionBar;

    private boolean inSeek = false;
    private boolean isCompleted = false;
//    String url = "http://player.alicdn.com/video/aliyunmedia.mp4";
    String url = "http://ksmvmt.video.meipai.com/5acf576fb0f524700_H264_11.mp4?k=62a700cf697ab7857041ca42f1f2cb30&t=5adbf435";
    private AliVcMediaPlayer mPlayer;

    private NetWatchdog netWatchdog;

    private long lastSeekTime = -1;

    private AlertDialog netChangeDialog = null;

    private boolean isxian = true;

    private Handler progressUpdateTimer = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    showVideoProgressInfo();
                    break;
                case 1:
                    progress_layout.setVisibility(View.GONE);
                    aniu.setVisibility(View.GONE);
                    break;
                case 2:
                    progress_layout.setVisibility(View.VISIBLE);
                    aniu.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_video);
        ViewInjectUtils.inject(this);
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).init();
        initView();

    }


    public void initView() {
        initVodPlayer();
        start();
        progressUpdateTimer.sendEmptyMessageDelayed(1, 3000);
        aniu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer.isPlaying()) {
                    pause();
                    aniu.setText("继续");
                } else {
                    resume();
                    aniu.setText("暂停");
                }
            }
        });

        mSurfaceView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isxian == true) {
                    progressUpdateTimer.sendEmptyMessage(1);
                    isxian = false;
                } else {
                    progressUpdateTimer.sendEmptyMessage(2);
                    isxian = true;
                }


            }
        });

        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mPlayer != null) {
                    seekTo(seekBar.getProgress());

                    Log.d("lfj0929", "onStopTrackingTouch , inSeek= " + inSeek);
                }
            }
        });

        quanpin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2018/4/16 0016 全屏~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                int orientation = getResources().getConfiguration().orientation;
                if (orientation == Configuration.ORIENTATION_PORTRAIT) {                //转为竖屏了。
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏

                } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {                //转到横屏了。
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
                }

            }
        });
    }

    private void initVodPlayer() {

        mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            public void surfaceCreated(SurfaceHolder holder) {
//                holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
                holder.setKeepScreenOn(true);
                Log.e("妈个鸡", "surfaceCreated ");
                // Important: surfaceView changed from background to front, we need reset surface to mediaplayer.
                // 对于从后台切换到前台,需要重设surface;部分手机锁屏也会做前后台切换的处理
                if (mPlayer != null) {
                    mPlayer.setVideoSurface(holder.getSurface());
                }

            }

            public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

                Log.e("妈个鸡", "surfaceChanged ");
                if (mPlayer != null) {
                    mPlayer.setSurfaceChanged();
                }
            }

            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.e("妈个鸡", "surfaceDestroyed ");
//                if (mPlayer != null) {
//                    mPlayer.releaseVideoSurface();
//                }
            }
        });

        mPlayer = new AliVcMediaPlayer(this, mSurfaceView);
//开启缓存
//        String sdDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test_save_cache";
//        mPlayer.setPlayingCache(true, sdDir, 60 * 60 /*时长, s */, 300 /*大小，MB*/);
//开启循环播放
//        mPlayer.setCirclePlay(true);

        mPlayer.setPreparedListener(new MyPrepareListener(this));
        mPlayer.setPcmDataListener(new MyPcmDataListener(this));
        mPlayer.setCircleStartListener(new MyCircleStartListener(this));
        mPlayer.setFrameInfoListener(new MyFrameInfoListener(this));
        mPlayer.setErrorListener(new MyErrorListener(this));
        mPlayer.setCompletedListener(new MyCompletedListener(this));
        mPlayer.setSeekCompleteListener(new MySeekCompleteListener(this));
        mPlayer.setStoppedListener(new MyPlayerStoppedListener(this));
        //打开、关闭播放器日志
//        mPlayer.enableNativeLog();
        mPlayer.disableNativeLog();

        netWatchdog = new NetWatchdog(this);
        netWatchdog.setNetChangeListener(new NetWatchdog.NetChangeListener() {
            @Override
            public void onWifiTo4G() {
                if (mPlayer.isPlaying()) {
                    pause();
                }
                if (netChangeDialog == null || !netChangeDialog.isShowing()) {
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(VideoActivity.this,R.style.MyAlertDialogStyle);
                    alertDialog.setTitle("网络切换为4G");
                    alertDialog.setMessage("是否继续播放？");
                    alertDialog.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            int playerState = mPlayer.getPlayerState();
                            if (playerState == AliVcMediaPlayer.STOPPED) {
                                seekTo(progressBar.getProgress());
                                mPlayer.prepareAndPlay(url);
                            } else if (playerState == AliVcMediaPlayer.PAUSED) {
                                resume();
                            } else {
                                stop();
                                seekTo(progressBar.getProgress());
                                start();
                            }
                        }
                    });
                    alertDialog.setNegativeButton(getString(R.string.no), null);
                    netChangeDialog = alertDialog.create();
                    netChangeDialog.show();
                }

//                Toast.makeText(VideoActivity.this.getApplicationContext(), "网络切换为4G", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void on4GToWifi() {
//                Toast.makeText(VideoActivity.this.getApplicationContext(), "网络切换为WIFI", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onNetDisconnected() {
//                Toast.makeText(VideoActivity.this.getApplicationContext(), "网络已断开", Toast.LENGTH_SHORT).show();
            }
        });
        netWatchdog.startWatch();

    }

    private void seekTo(int position) {
        if (mPlayer == null) {
            return;
        }

        if (isCompleted) {
            inSeek = false;
            return;
        }


        if (lastSeekTime < 0) {
            lastSeekTime = System.currentTimeMillis();

            inSeek = true;
            mPlayer.seekTo(position);
        } else {
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastSeekTime > 1000) {//1000ms
                inSeek = true;
                mPlayer.seekTo(position);
                lastSeekTime = currentTime;
            }
        }

    }

    private static class MyPrepareListener implements MediaPlayer.MediaPlayerPreparedListener {
        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MyPrepareListener(VideoActivity videoActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(videoActivity);
        }

        @Override
        public void onPrepared() {
            VideoActivity videoActivity = vodModeActivityWeakReference.get();
            if (videoActivity != null) {
                videoActivity.onPrepared();
            }
        }
    }

    private void onPrepared() {

        mPlayer.play();
        inSeek = false;
    }

    private static class MyPcmDataListener implements MediaPlayer.MediaPlayerPcmDataListener {

        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MyPcmDataListener(VideoActivity vodModeActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(vodModeActivity);
        }


        @Override
        public void onPcmData(byte[] bytes, int i) {
            VideoActivity vodModeActivity = vodModeActivityWeakReference.get();
            if (vodModeActivity != null) {
                vodModeActivity.onPcmData(bytes, i);
            }
        }
    }

    private void onPcmData(byte[] bytes, int i) {
        //pcm数据获取到了
    }

    private static class MyCircleStartListener implements MediaPlayer.MediaPlayerCircleStartListener {
        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MyCircleStartListener(VideoActivity vodModeActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(vodModeActivity);
        }

        @Override
        public void onCircleStart() {

            VideoActivity vodModeActivity = vodModeActivityWeakReference.get();
            if (vodModeActivity != null) {
                vodModeActivity.onCircleStart();
            }
        }
    }

    private void onCircleStart() {
        //循环播放开始
        Log.d("lfj0929", "MediaPlayerCircleStartListener onCircleStart  ");
    }

    private static class MyFrameInfoListener implements MediaPlayer.MediaPlayerFrameInfoListener {

        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MyFrameInfoListener(VideoActivity vodModeActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(vodModeActivity);
        }

        @Override
        public void onFrameInfoListener() {
            VideoActivity vodModeActivity = vodModeActivityWeakReference.get();
            if (vodModeActivity != null) {
                vodModeActivity.onFrameInfoListener();
            }
        }
    }

    private void onFrameInfoListener() {
        inSeek = false;
        showVideoProgressInfo();

    }

    private void showVideoProgressInfo() {

        if (mPlayer != null) {

            int curPosition = (int) mPlayer.getCurrentPosition();
            int duration = (int) mPlayer.getDuration();
            int bufferPosition = mPlayer.getBufferPosition();
            Log.d("lfj0929", "curPosition = " + curPosition + " , duration = " + duration + " ， inSeek = " + inSeek);

            if (!inSeek) {
                positionTxt.setText(Formatter.formatTime(curPosition));
                durationTxt.setText(Formatter.formatTime(duration));
                progressBar.setMax(duration);
                progressBar.setSecondaryProgress(bufferPosition);
                progressBar.setProgress(curPosition);
            }
        }

        startUpdateTimer();
    }

    private void startUpdateTimer() {
        progressUpdateTimer.removeMessages(0);
        progressUpdateTimer.sendEmptyMessageDelayed(0, 1000);
    }


    private static class MyErrorListener implements MediaPlayer.MediaPlayerErrorListener {

        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MyErrorListener(VideoActivity vodModeActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(vodModeActivity);
        }


        @Override
        public void onError(int i, String msg) {
            VideoActivity vodModeActivity = vodModeActivityWeakReference.get();
            if (vodModeActivity != null) {
                vodModeActivity.onError(i, msg);
            }
        }
    }

    private void onError(int i, String msg) {
        pause();
        Toast.makeText(VideoActivity.this.getApplicationContext(), "失败！！！！原因：" + msg, Toast.LENGTH_SHORT).show();
        LsfbLog.e( "失败！！！！原因：" + msg);
    }

    private static class MyCompletedListener implements MediaPlayer.MediaPlayerCompletedListener {

        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MyCompletedListener(VideoActivity vodModeActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(vodModeActivity);
        }

        @Override
        public void onCompleted() {
            VideoActivity vodModeActivity = vodModeActivityWeakReference.get();
            if (vodModeActivity != null) {
                vodModeActivity.onCompleted();
            }
        }
    }

    private void onCompleted() {
        isCompleted = true;
        showVideoProgressInfo();
        stopUpdateTimer();
    }

    private void stopUpdateTimer() {
        progressUpdateTimer.removeMessages(0);
    }

    private static class MySeekCompleteListener implements MediaPlayer.MediaPlayerSeekCompleteListener {


        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MySeekCompleteListener(VideoActivity vodModeActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(vodModeActivity);
        }

        @Override
        public void onSeekCompleted() {
            VideoActivity vodModeActivity = vodModeActivityWeakReference.get();
            if (vodModeActivity != null) {
                vodModeActivity.onSeekCompleted();
            }
        }
    }

    private void onSeekCompleted() {
        inSeek = false;
        Log.d("lfj0929", "MediaPlayerSeekCompleteListener inSeek = " + inSeek);
    }

    private static class MyPlayerStoppedListener implements MediaPlayer.MediaPlayerStoppedListener {

        private WeakReference<VideoActivity> vodModeActivityWeakReference;

        public MyPlayerStoppedListener(VideoActivity vodModeActivity) {
            vodModeActivityWeakReference = new WeakReference<VideoActivity>(vodModeActivity);
        }

        @Override
        public void onStopped() {
            VideoActivity vodModeActivity = vodModeActivityWeakReference.get();
            if (vodModeActivity != null) {

            }
        }
    }


    private void start() {

        Log.e("lfj0929", "VodmodeAtivity start() mPlayer  =  " + mPlayer);
        if (mPlayer != null) {
            mPlayer.prepareToPlay(url);
        }
    }

    private void pause() {
        if (mPlayer != null) {
            mPlayer.pause();
            aniu.setText("继续");
        }
    }

    private void stop() {

        if (mPlayer != null) {
            mPlayer.stop();
        }
    }

    private void resume() {
        if (mPlayer != null) {
            VcPlayerLog.d("lfj0927", "mPlayer.play");
            mPlayer.play();
            aniu.setText("暂停");
        }
    }

    private void destroy() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.destroy();
        }
    }

    private void replay() {
        Log.d("lfj0929", "VodmodeAtivity replay()");
        stop();
        start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        LsfbEvent.getInstantiation().register2(this);
        Log.e("妈个鸡", "VodmodeAtivity onResume()");

    }

    @Override
    protected void onStop() {
        super.onStop();
        //when view goto background,will pausethe player, so we save the player's status here,
        // and when activity resumed, we resume the player's status.
        savePlayerState();
        Log.e("妈个鸡", "VodmodeAtivity onStop()");
        LsfbEvent.getInstantiation().unregister2(this);
    }

    private void savePlayerState() {
        if (mPlayer.isPlaying()) {
            //we pause the player for not playing on the background
            // 不可见，暂停播放器
            pause();
        }
    }

    @Override
    protected void onDestroy() {
        stop();
        destroy();
        stopUpdateTimer();
        progressUpdateTimer = null;
        netWatchdog.stopWatch();
        Log.e("妈个鸡", "VodmodeAtivity onDestroy()");
        super.onDestroy();
        mImmersionBar.destroy();  //在BaseActivity里销毁
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {                //转为竖屏了。
            //显示状态栏
            LsfbLog.e("竖屏了");
            this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

            //设置view的布局，宽高之类
            ViewGroup.LayoutParams surfaceViewLayoutParams = mSurfaceView.getLayoutParams();
            surfaceViewLayoutParams.height = (int) (getWight(this) * 9.0f / 16);
            surfaceViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;

        } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {                //转到横屏了。
            //隐藏状态栏
            LsfbLog.e("横屏了");
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mSurfaceView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN);
            //设置view的布局，宽高
            ViewGroup.LayoutParams surfaceViewLayoutParams = mSurfaceView.getLayoutParams();
            surfaceViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
            surfaceViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;

        }
    }

    public static int getWight(Context mContext) {
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        return screenWidth;
    }

}
